#include "qtch/qtch.h"

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>

static qtch::Logger::ptr logger = QTCH_LOG_NAME("test");

void test_sleep(){
    qtch::IOManager iom(1);
    iom.schedule([](){
        QTCH_LOG_INFO(logger) << "begin sleep 2";
        sleep(2);
        QTCH_LOG_INFO(logger) << "sleep 2";
    });
    iom.schedule([](){
        QTCH_LOG_INFO(logger) << "begin sleep 3";
        sleep(3);
        QTCH_LOG_INFO(logger) << "sleep 3";
    });
    QTCH_LOG_INFO(logger) << "test_sleep";
    iom.start();
}

void test_socket(){

    int sock = socket(AF_INET, SOCK_STREAM, 0);

    sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(6666);
    inet_pton(AF_INET, "192.168.134.16", &addr.sin_addr.s_addr);
    QTCH_LOG_INFO(logger) << "begin connect";
    int rt = connect(sock, (const sockaddr*)&addr, sizeof(addr));
    QTCH_LOG_INFO(logger) << "connect rt=" << rt << " errno=" << errno;

    if(rt) {
        return;
    }

    const char data[] = "GET / HTTP/1.0\r\n\r\n";
    rt = send(sock, data, sizeof(data), 0);
    QTCH_LOG_INFO(logger) << "send rt=" << rt << " errno=" << errno;

    if(rt <= 0) {
        return;
    }

    std::string buff;
    buff.resize(4096);
    while(1){
        rt = recv(sock, &buff[0], buff.size(), 0);
        QTCH_LOG_INFO(logger) << "recv=" << buff;
        const char *x = buff.c_str();
        sleep(1);
        rt = send(sock, x, strlen(x), 0);
    }

    if(rt <= 0) {
        return;
    }

    buff.resize(rt);
    QTCH_LOG_INFO(logger) << buff;
}

void test(){
    qtch::IOManager iom(1);
    iom.schedule(test_socket);
    // iom.addTimer(1000,[](){
    //     QTCH_LOG_INFO(logger) <<"test";
    // },true);
    iom.start();
}

void testMutex(){
    qtch::Mutex mutex;
    QTCH_LOG_INFO(logger) << "1";
    qtch::Mutex::Lock lock(mutex);
    QTCH_LOG_INFO(logger) << "2";
    qtch::Mutex::Lock lock2(mutex);
    QTCH_LOG_INFO(logger) << "3";
}
int main(){
    // test_sleep();
    test();

}